<template>
  <div class="m-pageView">
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>分配权限</div>
        <div class="layout-2">
          <el-form :inline="true">
            <el-form-item label="角色名称">
              <el-input v-model="$route.query.name" readonly></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="m-tree el-card">
        <el-tree
          ref="roleTree"
          :data="permissionData"
          show-checkbox
          node-key="id"
          :props="{children: 'children',label: 'label'}"
          @check="treeCheckChange">
        </el-tree>
      </div>
      <div>
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="onRoleUpdate">更新</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import * as roleAPI from "@/Api/role";
  export default {
    name: "GrantPermissions",
    data() {
      return {
        roleId: "",
        checkedKeys: [],
        permissionData: [],
        idGroup: {},
      };
    },
    created() {
      this.queryData()
        .then(() => {
          this.requestRole();
        })
        .catch(error => {
          console.log(error);
        })
    },
    computed: {
      roles() {
        return this.$store.state.app.userInfo.roles
      }
    },
    methods: {
      requestCurrentPerm(roleId) {
        roleAPI.rolePermQueryById({
          roleId: roleId
        })
          .then(res => {
            if (res.code != '0') {
              this.$notify({
                title: "温馨提示",
                message: res.msg,
                type: "warning"
              });
              return;
            }
            let dataArr = res.data.map(item => item.id.toString());
            var checkedKeys = [];
            new Set(dataArr).forEach(id => checkedKeys.push(id));
            this.$refs.roleTree.setCheckedKeys(checkedKeys);
            this.checkedKeys = checkedKeys;
          })
          .catch(error => {
            console.log(error);
          });
      },
      requestRole() {
        roleAPI.roleQuery({
          roleName: this.$route.query.name
        })
          .then(res => {
            if (res.code != '0') {
              this.$notify({
                title: "温馨提示",
                message: res.msg,
                type: "warning"
              });
              return;
            }
            this.roleId = res.data[0].id;
            this.requestCurrentPerm(res.data[0].id);
          })
          .catch(error => {
            console.log(error);
          });
      },
      rearrangePermissionData(permissionData) {
        let result = [],
          nameSet = {},
          index;
        permissionData.forEach(row => {
          let type = row.name.slice(0, row.name.indexOf("-"));
          if (nameSet.hasOwnProperty(type)) {
            index = nameSet[type];
            result[index].children.push({
              id: row.id,
              label: row.name.slice(row.name.indexOf("-") + 1)
            });
          } else {
            index = result.length;
            nameSet[type] = result.length;
            result.push({
              id: Math.random()
                .toString()
                .slice(2),
              label: type,
              children: [
                {
                  id: row.id,
                  label: row.name.slice(row.name.indexOf("-") + 1)
                }
              ]
            });
          }
        });
        let root = result.find(row => row.label === "界面"),
          resultForTree;
        result.forEach(row => {
          if (row.label === "界面") {
            return;
          }
          root.children.forEach(child => {
            if (child.label === row.label) {
              row.id = child.id;
            }
          });
        });
        resultForTree = result.filter(row => row.label !== "界面");
        this.idGroup = {};
        resultForTree.forEach(item => {
          if (!this.idGroup.hasOwnProperty('_' + item.id)) {
            this.idGroup['_' + item.id] = [];
          }
          item.children.forEach(childenItem => {
            this.idGroup['_' + item.id].push(childenItem.id.toString())
          })
        })
        return resultForTree;
      },
      queryData() {
        return new Promise((reslove, reject) => {
          roleAPI.rolePermQuery()
            .then(res => {
              if (res.code != '0') {
                this.$notify({
                  title: "温馨提示",
                  message: res.msg,
                  type: "warning"
                });
                reject(res.msg);
                return;
              }
              this.permissionData = this.rearrangePermissionData(res.data);
              reslove();
            })
            .catch(error => {
              reject(error);
              console.log(error);
            })
        })
      },
      treeCheckChange(node, props) {
        this.checkedKeys = props.checkedKeys
          .slice(0)
          .concat(props.halfCheckedKeys);
      },
      onRoleUpdate() {
        let result = [].concat(this.checkedKeys);
        result.forEach(item => {
          if (!this.idGroup.hasOwnProperty('_' + item)) {
            for (let key in this.idGroup) {
              if (this.idGroup[key].indexOf(item) >= 0) {
                if (result.indexOf(key.split('_')[1]) < 0) {
                  console.log(key.split('_')[1])
                  result.unshift(key.split('_')[1]);
                }
                break;
              }
            }
          }
        })
        roleAPI.rolePerm({
          roleId: this.roleId,
          perm: result.join("|")
        })
          .then(res => {
            if (res.code != 0) {
              this.$notify({
                title: "温馨提示",
                message: res.msg,
                type: "warning"
              });
              return;
            }
            if (this.roleId == this.roles) {
              window.location.reload()
            }
            this.$message({
              type: "success",
              message: `已经成功为${this.$route.query.name}修改权限!`
            });
          })
          .catch(error => {
            console.log(error);
          });
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "../../scss/variables";

  .m-tree {
    width: 500px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    padding: 10px;
    margin-bottom: 20px;
  }
</style>
